package com.cwg.dict.service.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;

import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.exception.NestableRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileHelper {

	private static final String	DICTIONARIES_FOLDER_NAME	= "dicts";

	private File				homeDirectory;
	private Logger				logger						= LoggerFactory.getLogger(FileHelper.class);

	public File getHomeDirectory() {
		return homeDirectory;
	}

	public void setHomeDirectory(File homeDirectory) {
		this.homeDirectory = homeDirectory;
	}

	protected File[] allDictDirectories() {
		FilenameFilter filter = DirectoryFileFilter.INSTANCE;
		File[] results = getDictsDirectory().listFiles(filter);
		logger.info("found {} dictionary folders", results.length);
		return results;
	}

	protected File getDictsDirectory() {
		if (!homeDirectory.isDirectory()) {
			String msg = homeDirectory.getAbsolutePath() + " is not directory";
			logger.error(msg);
			throw new NestableRuntimeException(msg);
		}

		FileFilter filter = DirectoryFileFilter.INSTANCE;
		for (File each : homeDirectory.listFiles(filter)) {
			if (StringUtils.equalsIgnoreCase(DICTIONARIES_FOLDER_NAME, each.getName())) {
				return each;
			}
		}
		return null;
	}

	protected File getSoundFile(String word) throws FileNotFoundException {
		// TODO: support multiple source pronounce dir 
		File soundsDir = new File(homeDirectory, "sounds" + File.separator + "WyabdcRealPeopleTTS");
		File initialDir = new File(soundsDir, StringUtils.substring(word, 0, 1));
		File soundFile = new File(initialDir, word + ".wav");
		logger.info("play sound file " + soundFile.getAbsolutePath());
		if (!soundFile.exists() || !soundFile.isFile()) {
			throw new FileNotFoundException(soundFile.getAbsolutePath());
		}
		return soundFile;
	}
}
